from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from Response import Response
from Connection import Connection
import Tag
import re
import os
from google.appengine.ext.webapp import template
from Logic import Logic

'''
@author: Tobias Wilken

Copyright ....


This file is used for the web interface.
Two pages are defined:
 - /admin - to add new responses or to delete existing ones
            for this are two additionals urls are used: /add and /delete
 - /test - to test the robot outside of google wave
'''

'''
The AdminPage class show die page to administer the responses and tags.
 - It gives the possibilty to add responses, the tags are extracted from the text.
 - Existing responses can be deleted
'''
class AdminPage(webapp.RequestHandler):
	def get(self):
		# Get all responses from the database
		responses = db.GqlQuery("SELECT * FROM Response LIMIT 10")
		values = []
		# Iterate over the responses
		for response in responses:
			# Get the connections from the response
			query = Connection.gql("WHERE response = :1", response)
			connections = query.fetch(1000, 0)
			tags = ""
			# Iterate over the connections and concatenate them with kommatas to a string
			for connection in connections:
				value = -1
				tags += connection.tag.text + " " + str(connection.value) + ", "
			
			# Add the response and the tag string to the value list
			values.append({'response':response, 'tags':tags})

		# Prepare the values for the template
		template_values = {
			'values': values,
		}

		# forward the request to the 'admin.html' template
		path = os.path.join(os.path.dirname(__file__), 'admin.html')
		self.response.out.write(template.render(path, template_values))

'''
Redirects to the blog, the url have to be adepted
'''
class RedirectBlog(webapp.RequestHandler):
	def get(self):
		self.redirect("http://wave-helper.blogspot.com")


'''
TestPage class to test the robot without wave
'''
class TestPage(webapp.RequestHandler):
	def get(self):
		path = os.path.join(os.path.dirname(__file__), 'test.html')
		self.response.out.write(template.render(path, {'answer':''}))

	def post(self):
		text = self.request.get('content')
		logic = Logic()
		logic.findAnswer(text)
		if logic.answerPresent():
			template_values = {
				'answer': logic.getAnswer()
			}
		else:
			template_values = {
				'answer': ''
			}
		path = os.path.join(os.path.dirname(__file__), 'test.html')
		self.response.out.write(template.render(path, template_values))
			
'''
AddPage class to add new responses
'''
class AddPage(webapp.RequestHandler):
  def post(self):
	text = self.request.get('content')
	query = Response.gql("WHERE text = :1", text)
	response = query.get()
	if not response:
		response = Response()
		response.text = text
		response.put()

	subber = re.compile(r"[^A-Za-z0-9]").sub
	for word in text.split(" "):
		word = subber("", word)

		tag = Tag.getTag(word)

		query = Connection.gql("WHERE tag = :1 AND response = :2", tag, response)
		connection = query.get()
		if connection:
			connection.value += 1
			connection.put()
		else:
			connection = Connection()
			connection.tag = tag
			connection.response = response
			connection.value = 1
			connection.put()
	
	self.redirect('/admin')

'''
DeletePage class to delete resonses
'''
class DeletePage(webapp.RequestHandler):
  def post(self):
	text = self.request.get('response')
	query = Response.gql("WHERE text = :1", text)
	response = query.get()
	if response:
		query = Connection.gql("WHERE response = :1", response)
		connections = query.fetch(1000, 0)
		for connection in connections:
			connection.delete()
		response.delete()
	self.redirect('/admin')

'''
Handler for the different urls
'''
application = webapp.WSGIApplication([
						('/', RedirectBlog),
						('/test', TestPage), 
						('/admin', AdminPage), 
						('/add', AddPage), 
						('/delete', DeletePage)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
